import decimal
import random
import time

import requests

from orderSharing.retailOrderSharing import RetailOrderSharing


class ShoppingCart:

    token = ""
    goodSku = None

    def __init__(self):
        self.retailOrderSharing = RetailOrderSharing()

    def settlement_shopping_cart(self):

        userList = self.retailOrderSharing.session.execute("select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id, ru.current_retail_store_id\
                                            from retail_users ru\
                                            inner join user_addresses ua on ru.user_id = ua.user_id\
                                            inner join users u on u.id = ru.user_id\
                                            where ru.is_real_name = 1 and ua.is_default = 1").fetchall()
        user = userList[random.randint(0, len(userList) - 1)]
        # user = userList[0]

        vip_level = self.retailOrderSharing.session.execute(
            "select vip_level from retail_vips where user_id = :userId limit 1",
            params={"userId": user[0]}).first()
        print("vip_level：", vip_level)

        requests.request("POST", url="https://test.api.vodeshop.com/api/sms/user-login", json={"mobile": user[1]})
        time.sleep(5)

        print("user：", user)
        userToken = requests.request("POST", url="https://test.api.vodeshop.com/api/auth/login/mobile",
                                     json={"mobile": user[1], "password": "", "code": "111111"}).json()
        print("userToken：", userToken)
        self.token = userToken["data"]["token_type"] + " " + userToken["data"]["access_token"]

        goodList = requests.request("GET", url="https://test.api.vodeshop.com/api/retail/mall/index-goods?page=" + str(
            random.randint(1, 4)), headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                            "authorization": self.token}).json()["data"]["data"]

        w = 0
        while w <= 3:
            good = goodList[random.randint(0, 14)]
            print("good：", good)

            goodSkuList = requests.request("GET",
                                           url="https://test.api.vodeshop.com/api/retail/goods/show?retail_goods_id=" + str(
                                               good["id"]),
                                           headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                    "authorization": self.token}).json()["data"]["goods_skus"]
            if len(goodSkuList) == 1:
                self.goodSku = goodSkuList[0]
            elif len(goodSkuList) > 1:
                self.goodSku = goodList[random.randint(0, random.randint(0, len(goodSkuList) - 1))]
            print("goodSku：", self.goodSku)

            goodTotal = random.randint(2, 3)

            requests.request("POST", url="https://test.api.vodeshop.com/api/retail/cart/store",
                             headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                      "authorization": self.token},
                             json={"goods_id": good["id"], "goods_sku_id": self.goodSku["id"],
                                   "goods_total": goodTotal})

            w += 1

        cart = requests.request("GET", url="https://test.api.vodeshop.com/api/retail/cart",
                                   headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                            "authorization": self.token}).json()

        cartGoodList = cart["data"]["normal"][0]["items"]

        retail_goods_id_list = []
        confirm_good_list = []
        cart_id_list = []
        for cartGood in cartGoodList:
            retail_goods_id_list.append(cartGood["retail_goods_id"])

            confirm_good = {}
            confirm_good["goods_sku_id"] = cartGood["retail_goods_sku_id"]
            confirm_good["goods_total"] = cartGood["goods_total"]
            confirm_good_list.append(confirm_good)

            cart_id_list.append(cartGood["id"])

        orderCheck = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/check-order",
                                      headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                               "authorization": self.token},
                                      json={"retail_goods_id": retail_goods_id_list, "address_id": user[2]}).json()
        confirm = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/order/confirm",
                                   headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                            "authorization": self.token},
                                   json={"goods": confirm_good_list,
                                         "cart_id": cart_id_list, "address_id": user[2]}).json()
        print("confirm：", confirm)
        order = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/order/order",
                                 headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                          "authorization": self.token},
                                 json={"goods": confirm_good_list,
                                       "cart_id": cart_id_list, "address_id": user[2], "pay_type": 1, "purchase_way": 0}).json()
        print("order：", order)
        self.retailOrderSharing.session.commit()
        retail_sets = self.retailOrderSharing.session.execute(
            "select credit_ratio, bind_store_ratio, current_store_ratio, agent_ratio from retail_sets limit 1").first()

        itemList = confirm["data"]["goods"][0]["items"]
        price = decimal.Decimal("0.00")
        sub_price = decimal.Decimal("0.00")
        for item in itemList:
            price += item["goods_total"] * decimal.Decimal(item["goods_sku"]["price"])

            sub_price += item["goods_total"] * decimal.Decimal(item["goods_sku"]["sub_price"])

        addr_carriage_price = decimal.Decimal("0.00")
        for addr_carriage in orderCheck["data"]:
            for addr_item in itemList:
                if addr_item["goods_id"] == addr_carriage["id"]:
                    addr_carriage_price += decimal.Decimal(addr_carriage["addr_carriage"]) * addr_item["goods_total"]

        amount = price + addr_carriage_price - sub_price
        print("amount：", amount)
        self.retailOrderSharing.session.commit()
        order_sn = self.retailOrderSharing.session.execute(
            "select order_sn from payments where user_id = :userId and targetable_id =:targetableId order by created_at desc limit 1",
            params={"userId": user[0], "targetableId": order["data"]["order_merge_id"]}).first()
        print("order_sn：", order_sn)

        res = requests.request("POST", url="https://test.api.vodeshop.com/api/v2/test/notifyyyy",
                               data={"out_trade_no": order_sn[0], "trade_no": order_sn[0], "total_amount": "1"}).json()
        print("res：", res)
        time.sleep(10)

        distributableProfit = decimal.Decimal("0.00")
        for sku in confirm_good_list:
            self.retailOrderSharing.session.commit()
            retail_goods_skus = self.retailOrderSharing.session.execute(
                "select price, cost_price, platform_profit_price from retail_goods_skus rgs where id = :skuId limit 1",
                params={"skuId": sku["goods_sku_id"]}).first()

            distributableProfit += (retail_goods_skus[0] - retail_goods_skus[1] - retail_goods_skus[2]) * sku["goods_total"]

        subRatioList = []
        for num in range(1, 3):
            self.retailOrderSharing.session.commit()
            sub_ratio = self.retailOrderSharing.session.execute(
                "select sub_ratio from retail_vip_levels where vip_level = :vipLevel limit 1",
                params={"vipLevel": num}).first()
            subRatioList.append(sub_ratio[0])

        crossStore = False
        self.retailOrderSharing.session.commit()
        retail_store_id = self.retailOrderSharing.session.execute(
            "select ro.retail_store_id, rog.id\
                    from retail_orders ro\
                    inner join retail_order_goods rog on rog.retail_order_id = ro.id\
                    where ro.id = :orderId limit 1", params={"orderId": order["data"]["order_id"]}).first()
        if user[3] != retail_store_id[0]:
            crossStore = True

        union, partner = 1, 1
        if vip_level != None:
            proportion = 0

            if vip_level[0] == 1:
                union += 1
                proportion = subRatioList[0]

            elif vip_level[0] == 2:
                partner += 1
                proportion = subRatioList[1]

            elif vip_level[0] == 3:
                if crossStore == False:
                    proportion = 100 - retail_sets[3]
                else:
                    proportion = 100 - retail_sets[3] - retail_sets[2]

            if decimal.Decimal(confirm["data"]["sub_price"]) != distributableProfit * proportion / 100:
                print("{}购物车结算页面会员立减错误，预期{}，实际{}".format(user[0], distributableProfit * proportion / 100,
                                                      decimal.Decimal(confirm["data"]["sub_price"])))

        # for singleItem in itemList:
        #     single_order_check = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/check-order",
        #                                   headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
        #                                            "authorization": self.token},
        #                                   json={"retail_goods_id": [singleItem["goods"]["id"]], "address_id": user[2]}).json()
        #
        #     single_price = singleItem["goods_total"] * (decimal.Decimal(singleItem["goods_sku"]["price"]) + decimal.Decimal(
        #         single_order_check["data"][0]["addr_carriage"]) - decimal.Decimal(singleItem["goods_sku"]["sub_price"]))
        #
        #     self.retailOrderSharing.session.commit()
        #     single_retail_goods_skus = self.retailOrderSharing.session.execute(
        #         "select price, cost_price, platform_profit_price from retail_goods_skus rgs where id = :skuId limit 1",
        #         params={"skuId": singleItem["goods_sku"]["id"]}).first()
        #
        #     self.retailOrderSharing.check_members_sharing(user[0], retail_store_id[1], single_price, subRatioList,
        #                                (single_retail_goods_skus[0] - single_retail_goods_skus[1] - single_retail_goods_skus[2]) * singleItem["goods_total"],
        #                                retail_sets, 1, union, partner, crossStore, user[3], retail_store_id[0],
        #                                vip_level)
        #
        #     print("----------------------------------------------------------------------------------------------------------------------------------------")


if __name__ == "__main__":
    ShoppingCart().settlement_shopping_cart()



















